package touro.mancala.master;

import java.io.OutputStream;
import java.net.Socket;
import java.util.Hashtable;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

import touro.mancala.slave.Board;

public class RequestManager implements Runnable {
	
	private static final Logger logger = Logger.getLogger(RequestManager.class.getName());

	private LinkedBlockingQueue<Request> requests;
	private Hashtable<Integer, Request> requestsMap;
	private Server server;
	
	public RequestManager( Server server ) {
		this.server = server;
		this.requests = new LinkedBlockingQueue<Request>();
		this.requestsMap = new Hashtable<Integer, Request>();
	}

	@Override
	public void run() {
		LinkedBlockingQueue<Socket> slaves = server.getSlaveManager().getSlaves();
		Socket slave = null;
		
		while ( true ) {
			try {
				logger.log(Level.INFO, "taking a request");
				Request r = requests.take();
				
				logger.log(Level.INFO, "processing request");
				
				Board board = r.getBoard();
				int activePlayer = board.getActivePlayer();
				
				int startIndex;
				if(activePlayer == 0) startIndex = 0;
				else startIndex = 7;
//				 int startIndex = activePlayer - 6;
				 for(int i = startIndex; i < startIndex+6; i++){
					 if (board.isPitEmpty(i)){
						 continue;
					 }
					 slave = slaves.take();
					 OutputStream out = slave.getOutputStream();
					 String slaveBoard = r.getId() + " " + board + " " + i + " " + activePlayer + "\n";
					 logger.log(Level.INFO, "Write board: " + slaveBoard);
					 out.write(slaveBoard.getBytes());
					 out.flush();
				 }

				
			} catch (Exception e) {
				if ( slave != null ) {
					slaves.add(slave);
				}
				e.printStackTrace();
			}
			
		}
	}
	
	public void addRequest( Request request ) {
		requests.add(request);
		requestsMap.put(request.getId(),request);
	}

	public Hashtable<Integer, Request> getRequestsMap() {
		return requestsMap;
	}
	
}
